<?php

// Define constants for database access.
define("DBHOST","localhost");
define("DBUSER","leafadmin");
define("DBPASSWORD","public");
define("DBNAME","leaf");

// Open a connection to the database
$dbc = mysqli_connect(DBHOST, DBUSER, DBPASSWORD, DBNAME) or die('Unable to connect to database!');

// Check if there was a post with a message in it
if($_POST['message'] && $_POST['message'] != '') {
	
	$message = $_POST['message'];
	
	// Sanitize the input somewhat
	$message = mysqli_real_escape_string($dbc, trim($message));
	// Construct a query to insert the message
	$db_query = "INSERT INTO messages (message) VALUES ('$message')";
	// Execute the query
	mysqli_query($dbc, $db_query) or die('Error querying databse');
	// Call the function to send back the current list of messages
	send_results($dbc);
}

// If a new message isn't being added, just send the most resent messages back
else send_results($dbc);

// Close the databse connection
mysqli_close($dbc);

// This function takes care of sending back the list of messages in the database, it takes a databse connection
function send_results($dbc) {
	
	// Variable to store an array of messages from the database
	$response = array();
	// Create a query to get all of the messages
	$messages_query = "SELECT * FROM messages";
	// Query the database and store the resulting database resource
	$result = mysqli_query($dbc, $messages_query);
	
	// Loop through each row in the database and add the message to the array
	while($row = mysqli_fetch_assoc($result)) {
		$response[] = $row['message'];
	}
	// JSON encode the resulting array, reversed so the newest message is first, and echo it
	$JSON_response = json_encode(array_reverse($response));
	echo $JSON_response;
}


?>